<template>
  <div class="gauge">
    <canvas ref="speedometer" width="200" height="200"></canvas>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      currentSpeed: 0,
      targetSpeed: 0,
      maxSpeed: 360,
      animationDuration: 1000,
      startTime: null,
      radius: 100,
      tickCount: 37,
      startTime: null,
      randomSpeed: 0,
    };
  },
  computed: {
    ...mapGetters(["bgSpeed", "getWebSocket", "getConnectionStatus"]),
  },
  mounted() {
    this.setSpeed(0);
    setInterval(() => {
      this.randomSpeed = Math.floor(this.bgSpeed * 36);
      this.setSpeed(this.randomSpeed);
    }, 1); // 每隔 2 秒变化一次速度
  },
  methods: {
    cancleInterVal() {
      clearInterval(this.startTime);
    },
    actionGamepe() {
      this.startTime = setInterval(() => {
        let speedStick = {
          code: "speedStick",
          time: new Date().getTime(),
          targetSpeed: this.randomSpeed,
        };
        if (this.getConnectionStatus) {
          this.getWebSocket.send(JSON.stringify(speedStick));
        }
      }, 56); // 每隔 2 秒变化一次速度
    },
    normalizeAngle(angle) {
      while (angle < 0) {
        angle += 2 * Math.PI;
      }
      while (angle >= 2 * Math.PI) {
        angle -= 2 * Math.PI;
      }
      return angle;
    },
    drawSpeedometer(speed) {
      if (this.$refs.speedometer == undefined) {
        return;
      }
      const canvas = this.$refs.speedometer;
      const ctx = canvas.getContext("2d");
      const centerX = canvas.width / 2;
      const centerY = canvas.height / 2;

      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制外圈
      // ctx.beginPath();
      // ctx.arc(centerX, centerY, this.radius, 0, Math.PI * 2);
      // ctx.strokeStyle = "transparent";
      // ctx.lineWidth = 10;
      // ctx.stroke();

      // 绘制刻度
      ctx.save();
      ctx.translate(centerX, centerY);
      ctx.font = "9px Arial";
      ctx.textAlign = "center";
      for (let i = 0; i < this.tickCount; i++) {
        const speedValue = i * 10; // 计算刻度上的速度值
        const angle = -Math.PI / 2 + (i / (this.tickCount - 1)) * Math.PI * 2; // 计算刻度位置的角度
        const x = (this.radius - 20) * Math.cos(angle);
        const y = (this.radius - 20) * Math.sin(angle);
        const x2 = (this.radius - 60) * Math.cos(angle); // 调整 x 的位置
        const y2 = (this.radius - 60) * Math.sin(angle); // 调整 y 的位置
        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.lineTo(
          x + (i % 2 === 0 ? 15 : 10) * Math.cos(angle),
          y + (i % 2 === 0 ? 15 : 10) * Math.sin(angle)
        ); // 每隔 2 个刻度绘制长刻度
        ctx.strokeStyle = "#fff";
        ctx.lineWidth = i % 2 === 0 ? 2 : 1;
        ctx.stroke();
        if (i % 2 === 0 && i != 0) {
          ctx.fillText(
            speedValue,
            x2 + 25 * Math.cos(angle),
            y2 + 25 * Math.sin(angle) + 5
          ); // 显示速度值
        }
      }
      ctx.restore();
      // 绘制速度指针
      ctx.save();
      ctx.translate(centerX, centerY);
      let angle = -Math.PI / 2 + (speed / this.maxSpeed) * Math.PI * 2;
      angle = this.normalizeAngle(angle); // 确保角度在 0 到 2π 范围内
      ctx.rotate(angle); // 根据速度旋转指针

      // 绘制红色指针及其荧光效果
      ctx.shadowBlur = 10;
      ctx.shadowColor = "red";
      ctx.fillStyle = "red";
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(3, -3);
      ctx.lineTo(this.radius * 0.5, 0); // 将指针长度调整为半径的 80%
      ctx.lineTo(3, 3);
      ctx.closePath();
      ctx.fill();
      ctx.restore();

      // 绘制速度文本背景框
      ctx.save();
      ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
      const textWidth = ctx.measureText(`${speed} km/h`).width;
      const textHeight = 12; // 文本高度
      const padding = 5; // 背景框内边距
      ctx.fillRect(
        centerX - textWidth / 2 - padding,
        centerY + 40 - textHeight - padding,
        textWidth + 2 * padding,
        textHeight + 2 * padding
      );
      ctx.restore();

      // 绘制速度文本
      ctx.font = "12px Arial";
      ctx.fillStyle = "#fff";
      ctx.textAlign = "center";
      ctx.fillText(`${speed} km/h`, centerX, centerY + 40);
    },

    animateSpeed(timestamp) {
      if (!this.startTime) this.startTime = timestamp;
      const elapsed = timestamp - this.startTime;

      // 计算当前速度值
      this.currentSpeed +=
        (this.targetSpeed - this.currentSpeed) *
        (elapsed / this.animationDuration);

      // 绘制速度表盘
      this.drawSpeedometer(Math.round(this.currentSpeed));

      if (elapsed < this.animationDuration) {
        requestAnimationFrame(this.animateSpeed);
      } else {
        this.startTime = null;
      }
    },
    setSpeed(newSpeed) {
      this.targetSpeed = newSpeed;
      if (!this.startTime) requestAnimationFrame(this.animateSpeed);
    },
  },
};
</script>

<style lang="scss" scoped>
.gauge {
  width: 260px;
  height: 260px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-image: url("../../assets/images/gauge.png");
  display: flex;
  flex-flow: row;
  justify-content: center;
  align-items: center;
  /* background-color: transparent; */
  margin: 0 10px;
}
canvas {
  border-radius: 50%;
}
</style>
